<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>[(${moduleName})]</title>
	<link type="text/css" rel="stylesheet" th:href="@{${skinPath} + '/css.css'}"/>
	<link rel="stylesheet" href="../js/bootstrap/css/bootstrap.min.css" />
	<link href="../lte/css/font-awesome.min.css?v=4.4.0" rel="stylesheet">
	<style>
		i {
			margin-right: 3px;
		}
		.search-form input,select {
			vertical-align:middle;
		}
		.search-form select {
			width: 80px;
		}
		.search-form input:not([type="radio"]):not([type="button"]):not([type="checkbox"]) {
			width: 80px;
			line-height: 20px; /*否则输入框的文字会偏下*/
		}
		.search-box {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
		}
		.cond-span {
			display: flex;
			float: left;
			align-items: center;
			text-align: left;
			width: 25%;
			height: 32px;
			margin: 3px 0;
		}
		.condBtnSearch {
			display: inline-block;
			float: left;
		}
		.cond-title {
			margin: 0;
			padding-right: 3px;
			width: 35%;
			text-align: right;
		}
		.cond-ctl {
			width: 65%;
			align-items: center;
		}
		.cond-ctl input,select {
			width: 90% !important;
		}
		.cond-ctl input[name$='FromDate'],input[name$='ToDate'] {
			width: 38% !important;
			margin: 0 2px;
		}
		.cond-ctl select[name$='_cond'] {
			width: 25% !important;
			margin-right:3px;
		}
		.cond-ctl select[name$='_cond']+input {
			width: 65% !important;
		}
		.cond-ctl select[name$='_cond']+select {
			width: 65% !important;
		}

		[(${pageCss})]
	</style>
	<script src="../inc/common.js"></script>
	<script src="../js/jquery-1.9.1.min.js"></script>
	<script src="../js/jquery-migrate-1.2.1.min.js"></script>
	<script src="../inc/flow_js.jsp"></script>
	<script src="../js/jquery.raty.min.js"></script>
	<script src="../js/jquery-alerts/jquery.alerts.js" type="text/javascript"></script>
	<script src="../js/jquery-alerts/cws.alerts.js" type="text/javascript"></script>
	<link href="../js/jquery-alerts/jquery.alerts.css" rel="stylesheet" type="text/css" media="screen" />
	<script th:inline="javascript">
		var requestParams = [];
		[# th:each="json : ${aryParam}"]
		requestParams.push({name: '[(${paramName})]', value: '[(${paramVal})]'});
		[/]
	</script>
	<script th:src="@{'/flow/form_js/form_js_' + ${formCodeRelated} + '.jsp?parentId=' + ${parentId} + '&formCode=' + ${formCode} + '&formCodeRelated=' + ${formCodeRelated} + '&moduleCodeRelated=' + ${moduleCodeRelated} + '&pageType=' + ${pageType} + '&random=' +${random}}"></script>

	<script src="../js/jquery.bgiframe.js"></script>
	<link type="text/css" rel="stylesheet" th:href="@{${skinPath} + '/jquery-ui/jquery-ui-1.10.4.css'}" />
	<script src="../js/jquery-ui/jquery-ui-1.10.4.min.js"></script>

	<link href="../js/jquery-showLoading/showLoading.css" rel="stylesheet" media="screen" />
	<script type="text/javascript" src="../js/jquery-showLoading/jquery.showLoading.js"></script>

	<link rel="stylesheet" type="text/css" href="../js/datepicker/jquery.datetimepicker.css"/>
	<script src="../js/datepicker/jquery.datetimepicker.js"></script>
	<script src="../js/BootstrapMenu.min.js"></script>

	<script type="text/javascript" src="../js/jquery.editinplace.js"></script>
	<script src="../inc/map.js"></script>
	<script type="text/javascript" src="../js/jquery.toaster.js"></script>

	<link rel="stylesheet" href="../js/layui/css/layui.css" media="all">
	<link rel="stylesheet" href="../js/soul-table/soulTable.css" media="all">
	<script src="../js/layui/layui.js" charset="utf-8"></script>

	<script th:inline="javascript">
		var mapEditable = new Map();
		var mapEditableOptions = new Map();
		var mapCheckboxPresent = new Map;
		var mapEditable = new Map();
		var mapEditableOptions = new Map();
		var mapCheckboxPresent = new Map;
		var isEditInplace = [(${isEditInplace})];

		[# th:if="${isEditInplace}"]
			[# th:each="json : ${aryEditable}"]
				mapEditable.put("[(${json.fieldName})]", "[(${json.type})]");
			[/]
			[# th:each="json : ${aryEditableOpt}"]
				mapEditableOptions.put("[(${json.fieldName})]", "[(${json.opt})]");
			[/]
			[# th:each="json : ${aryChkPresent}"]
				mapCheckboxPresent.put("[(${json.fieldName})]", "[(${json.present})]");
			[/]
		[/]

		var curOrderBy = "[(${orderBy})]";
		var sort = "[(${sort})]";
		function doSort(orderBy) {
			if (orderBy==curOrderBy) {
				if (sort=="asc") {
					sort = "desc";
				}
				else {
					sort = "asc";

				}
			}
			window.location.href = "moduleListRelatePage.do?menuItem=[(${menuItem})]&code=[(${moduleCode})]&parentId=[(${parentId})]&formCode=[(${formCode})]&formCodeRelated=[(${formCodeRelated})]&moduleCodeRelated=[(${moduleCodeRelated})]&orderBy=" + orderBy + "&sort=" + sort + "&isNav=[(${isNav}])";
		}
	</script>
</head>
<body>
<div th:if="${isNav and hasTab}" class="tabs1Box">
	<div id="tabs1">
		<ul>
			<li th:each="json : ${aryTab}" th:id="${json.id}" th:attr="tagName=${json.name}">
				<th:block th:switch="${json.get('target')!=null and json.target eq 'newTab'}">
					<th:block th:case="true">
						<a href="javascript:;" th:title="${json.name}" th:onclick="addTab('[(${json.name})]', '[(${json.url})]')"><span>[(${json.name})]</span></a>
					</th:block>
					<th:block th:case="*">
						<a th:href="${json.url}" title="${json.name}"><span>[(${json.name})]</span></a>
					</th:block>
				</th:block>
			</li>
		</ul>
	</div>
	<script th:inline="javascript">
		o("menu[(${menuItem})]").className="current";
	</script>
</div>

<table th:if="${isQuery}" id="searchTable" class="percent98" width="98%" border="0" align="center" cellpadding="0" cellspacing="0">
	<tr>
		<td width="80%" height="28" align="left" style="padding-top:5px">
			<form id="searchForm" class="search-form" onsubmit="return false">
				<div class="search-box">
					[(${condsHtml})]
					<span class="cond-span">
                        <span class="cond-title">
							<button th:if="${isQuery}" class="layui-btn layui-btn-primary layui-btn-sm" type="submit" onclick="doQuery()" data-type="reload"><i class="fa fa-search"></i>搜索</button>
						</span>
					</span>
					<input type="hidden" name="code" th:value="${moduleCode}"/>
					<input type="hidden" name="formCodeRelated" th:value="${moduleCodeRelated}"/>
					<input type="hidden" name="formCode" th:value="${formCode}"/>
					<input type="hidden" name="parentId" th:value="${parentId}"/>
					<input type="hidden" name="op" value="search"/>
					<input type="hidden" name="menuItem" th:value="${menuItem}"/>
					<input type="hidden" name="moduleCodeRelated" th:value="${moduleCodeRelated}"/>
					<input type="hidden" name="mode" th:value="${mode}"/>
					<input type="hidden" name="tagName" th:value="${tagName}"/>
					[(${requestParamInputs})]
				</div>
			</form>
		</td>
	</tr>
</table>

<table class="layui-hide" id="table_list" th:attr="lay-filter=${moduleCodeRelated}"></table>
<script type="text/html" id="toolbar_list">
	<div class="layui-btn-container">
		<button th:if="${isBtnAddShow}" class="layui-btn layui-btn-sm layui-btn-primary layui-border-green" lay-event="add" title="增加"><i class="fa fa-plus-circle"></i></i></i>增加</button>
		<button th:if="${isBtnEditShow}" class="layui-btn layui-btn-sm layui-btn-primary layui-border-orange" lay-event="edit" title="修改"><i class="fa fa-pencil"></i>修改</button>
		<button th:if="${isBtnDelShow}" class="layui-btn layui-btn-sm layui-btn-primary layui-border-red" lay-event="delRows" title="删除"><i class="layui-icon layui-icon-delete"></i>删除</button>
		<button th:if="${isBtnImportShow}" class="layui-btn layui-btn-sm layui-btn-primary layui-border-green" lay-event="importXls" title="导入Excel文件"><i class="fa fa-arrow-circle-o-down"></i>导入</button>
		<button th:if="${isBtnExportShow}" class="layui-btn layui-btn-sm layui-btn-primary layui-border-green" lay-event="exportXls" title="导出Excel文件"><i class="fa fa-file-excel-o"></i>导出</button>
		<button th:each="json,stat : ${aryBtn}" class="layui-btn layui-btn-sm layui-btn-primary layui-border-green" th:attr="lay-event='event' + ${stat.index}">
			<i th:class="'fa ' + json.class"></i>
			[(${json.name})]
		</button>
		<button th:if="${isAdmin}" class="layui-btn layui-btn-sm layui-btn-primary layui-border-blue" lay-event="manage"><i class="layui-icon layui-icon-set"></i>管理</button>
	</div>
</script>
<th:block th:if="${isToolbar}">
<span id="switcher" style="cursor:pointer; position: absolute; display: none">
	<img id="switchBtn" src="../images/hide.png" title="显示/隐藏 查询区域"/>
</span>
<script th:inline="javascript">
	$(function() {
		[# th:if="${isQuery}"]
		var $box = $('#searchTable');
		var l = $box.offset().left + $box.width();
		var t = $box.offset().top;
		$('#switcher').css({'top': t + 'px', 'left': l + 'px'});

		var $btn = $('#switchBtn');
		var $form = $('#searchForm');
		$('#switcher').click(function() {
			if ($btn.attr('src').indexOf("show.png") != -1) {
				$form.show();
				$btn.attr('src', '../images/hide.png');
			}
			else {
				$form.hide();
				$btn.attr('src', '../images/show.png');
			}
		});
		[/]
	});
</script>
</th:block>
</body>
<script th:inline="javascript">
function initCalendar() {
	[# th:each="fieldName : ${dateFieldNamelist}"]
	$('#[(${fieldName})]').datetimepicker({
		lang: 'ch',
		timepicker: false,
		format: 'Y-m-d'
	});
	[/]
}

var tableData;
layui.config({
	base: '../js/',   // 第三方模块所在目录
	// version: 'v1.6.2' // 插件版本号
}).extend({
	soulTable: 'soul-table/soulTable',
	tableChild: 'soul-table/tableChild',
	tableMerge: 'soul-table/tableMerge',
	tableFilter: 'soul-table/tableFilter',
	excel: 'soul-table/excel',
});

layui.use(['table', 'soulTable'], function () {
	var table = layui.table;
	var soulTable = layui.soulTable;

	var colProps = [(${colProps})];
	table.render({
		elem: '#table_list'
		, toolbar: '#toolbar_list'
		, defaultToolbar: ['filter', 'print'/*, 'exports', {
				title: '提示'
				,layEvent: 'LAYTABLE_TIPS'
				,icon: 'layui-icon-tips'
			}*/]
		, drag: {toolbar: true}
		, method: 'post'
		, url: 'moduleListRelate.do?[(${queryStr})]'
		, cols: [
			colProps
		]
		, id: 'tableList'
		, page: true
		, unresize: false
		, limit: [(${pageSize})]
		[# th:if="${isAutoHeight}"]
		, height: 'full-98'
		[/]
		, parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
			return {
				"code": res.errCode, //解析接口状态
				"msg": res.msg, //解析提示文本
				"count": res.total, //解析数据长度
				"data": res.rows //解析数据列表
			};
		}
		,done: function(res, curr, count){
			tableData = res.data;
			soulTable.render(this);
		}
	});

	//头工具栏事件
	table.on('toolbar()', function (obj) {
		var checkStatus = table.checkStatus(obj.config.id);
		switch (obj.event) {
			case 'add':
				window.location.href = "moduleAddRelatePage.do?parentPageType=[(${parentPageType})]&code=[(${moduleCode})]&parentId=[(${parentId})]&menuItem=[(${menuItem})]&formCode=[(${formCode})]&moduleCodeRelated=[(${moduleCodeRelated})]&isNav=[(${isNav})]";
				break;
			case 'edit':
				var data = checkStatus.data;
				if (data.length == 0) {
					layer.msg('请选择记录');
					return;
				} else if (data.length > 1) {
					layer.msg('只能选择一条记录');
					return;
				}
				var id = data[0].id;
				edit(id);
				break;
			case 'delRows':
				var data = checkStatus.data;
				if (data.length == 0) {
					layer.msg('请选择记录');
					return;
				}

				var ids = '';
				for (var i in data) {
					var json = data[i];
					if (ids == '') {
						ids = json.id;
					} else {
						ids += ',' + json.id;
					}
				}

				del(ids);
				break;
			case 'importXls':
				window.location.href = "module_import_excel.jsp?formCode=[(${formCodeRelated})]&code=[(${moduleCode})]&moduleCodeRelated=[(${moduleCodeRelated})]&parentId=[(${parentId})]&menuItem=[(${menuItem})]";
				break;
			case 'exportXls':
				var cols = "";
				// 找出未隐藏的表头
				$("div[lay-id='" + obj.config.id + "']").find('.layui-table th').each(function () {
					if ($(this).data("field") && $(this).data("field") != "0" && $(this).data("field") != "colOperate") {
						if (!$(this).hasClass('layui-hide')) {
							if (cols == "") {
								cols = $(this).data("field");
							} else {
								cols += "," + $(this).data("field");
							}
						}
					}
				});

				// 生成表单，以post方式，否则IE11下，某些参数可能会有问题
				// 如果用window.open方式，则IE11中当含有coo_address、coo_address_cond时，接收到coo_address的值为?_address_cond=0?_address=，而chrome中不会
				var expForm = o("exportForm");
				if (expForm != null) {
					expForm.parentNode.removeChild(expForm);
				}
				expForm = document.createElement("FORM");
				document.body.appendChild(expForm);

				expForm.style.display = "none";
				expForm.target = "_blank";
				expForm.method = "post";
				expForm.action = "[(${expUrl})]";
				var fields = $(".search-form").serializeArray();
				jQuery.each( fields, function(i, field) {
					expForm.innerHTML += "<input name='" + field.name + "' value='" + field.value + "'/>";
				});
				expForm.innerHTML += "<input name='cols' value='" + cols + "'/>";
				expForm.submit();
				break;
			case 'manage':
				addTab("[(${moduleName})]", "visual/module_field_list.jsp?formCode=[(${formCodeRelated})]&code=[(${moduleCodeRelated})]");
				break;
				//自定义头工具栏右侧图标 - 提示
			case 'LAYTABLE_TIPS':
				layer.alert('这是工具栏右侧自定义的一个图标按钮');
				break;
			[# th:each="json,stat : ${aryBtnEvent}"]
				[# th:switch="${json.type}"]
					[# th:case="script"]
						case 'event[(${stat.index})]':
							[(${json.script})]
							break;
					[/]
					[# th:case="batchBtn"]
						case 'event[(${stat.index})]':
							var data = checkStatus.data;
							if (data.length == 0) {
								layer.msg('请选择记录');
								return;
							}

							var ids = '';
							for (var i in data) {
								var json = data[i];
								if (ids == '') {
									ids = json.id;
								} else {
									ids += ',' + json.id;
								}
							}
							jConfirm("您确定要[(${json.name})]么？", "提示", function (r) {
								if (!r) {
									return;
								} else {
									batchOp(ids, "[(${json.batchField})]", "[(${json.batchValue})]");
								}
							})
						break;
					[/]
					[# th:case="flowBtn"]
						case 'event[(${stat.index})]':
							[(${json.script})]
							addTab('[(${json.flowName})]', contextPath + 'flow_initiate1_do.jsp?typeCode=[(${json.flowTypeCode)]');
							break;
					[/]
				[/]
			[/]
		}
	});

	$(document).on('click','.layui-table-cell',function(){
		var $parent = $(this).parent();
		var dataIndex = $parent.parent().attr('data-index');
		// 如果所点的是数据行
		if (dataIndex >= 0) {
			var id = tableData[dataIndex].id;
			var fieldName = $parent.attr('data-field');
			editCol(this, id, fieldName);
		}
	})

	$('.search-form .layui-btn').on('click', function (e) {
		e.preventDefault();
		table.reload('tableList', {
			page: {
				curr: 1 //重新从第 1 页开始
			}
			, where: $('.search-form').serializeJsonObject()
		}, 'data');
	});

	//监听表格排序问题
	table.on('sort()', function (obj) { //注：sort lay-filter="对应的值"
		table.reload('tableList', { //testTable是表格容器id
			initSort: obj // 记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
			, where: {
				orderBy: obj.field //排序字段
				, sort: obj.type //排序方式
			}
		});
	});
});

$.fn.serializeJsonObject = function () {
	var json = {};
	var form = this.serializeArray();
	$.each(form, function () {
		if (json[this.name]) {
			if (!json[this.name].push) {
				json[this.name] = [json[this.name]];
			}
			json[this.name].push();
		} else {
			json[this.name] = this.value || '';
		}
	});
	return json;
};

function batchOp(ids, batchField, batchValue) {
	$.ajax({
		type: "post",
		url: "moduleBatchOp.do",
		contentType:"application/x-www-form-urlencoded; charset=iso8859-1",
		data: {
			code: "[(${moduleCodeRelated})]",
			ids: ids,
			batchField: batchField,
			batchValue: batchValue
		},
		dataType: "html",
		beforeSend: function(XMLHttpRequest){
			$("body").showLoading();
		},
		success: function(data, status){
			data = $.parseJSON(data);
			jAlert(data.msg, "提示");
			if (data.ret=="1") {
				doQuery();
			}
		},
		complete: function(XMLHttpRequest, status){
			$("body").hideLoading();
		},
		error: function(XMLHttpRequest, textStatus){
			// 请求出错处理
			alert(XMLHttpRequest.responseText);
		}
	});
}

// 用于工具条自定义按钮的调用
function getIdsSelected(onlyOne) {
	var ids = "";
	$(".cth input[type='checkbox'][value!='on']", grid.bDiv).each(function(i) {
		if($(this).is(":checked")) {
			if (ids=="")
				ids = $(this).val().substring(3);
			else
				ids += "," + $(this).val().substring(3);
		}
	});

	var selectedCount = 0;
	var ary = ids.split(",");
	if (ids!="") {
		selectedCount = ary.length;
	}
	if (selectedCount == 0) {
		return "";
	}

	if (selectedCount > 1 && onlyOne) {
		return "";
	}
	return ids;
}

function onLoad() {
	try {
		onModuleListLoaded();
	}
	catch(e) {}
}

function doQuery() {
	layui.table.reload('tableList');
}

function editCol(celDiv, id, colName) {
	if (!mapEditable.containsKey(colName)) {
		return;
	}

	var fieldType = mapEditable.get(colName).value.toLowerCase();
	var selectOptions = "";
	var opts = mapEditableOptions.get(colName);
	if (opts!=null) {
		selectOptions = opts.value;
	}
	
	// 该插件会上传值：original_value、update_value
	$(celDiv).editInPlace({
		field_type: fieldType,
		url: "moduleEditInPlace.do",
		saving_text: "保存中...",
		saving_image: "../images/loading.gif",
		select_text: "请选择",
		select_options: selectOptions,
		checkbox_present: mapCheckboxPresent.get(colName) != null ? mapCheckboxPresent.get(colName).value : "",
		params: "colName=" + colName + "&id=" + id + "&code=[(${moduleCodeRelated})]",
		error:function(obj) {
			alert(JSON.stringify(obj));
		},
		success:function(data) {
			data = $.parseJSON(data);
			if (data.ret==-1) { // 值未更改
				return;
			}
			else {
				$.toaster({
					"priority" : "info",
					"message" : data.msg
				});
			}
		}
	});
}

function initEditInPlace() {
	$('#grid tr').each(function() {
		var id = $(this).attr('id');
		$(this).children('td').each(function(i) {
			if (i==0) {
				return;
			}
			var k = i-1; // 第0列为checkbox
			for (var n=0; n<fieldArr.length; n++) {
				if (n==k) {
					var field = fieldArr[n];
					initEditCol($(this).children('div')[0], id, field);
				}
			}
		});
	});
}

$(function() {
	initCalendar();

	var isEditInplace = [(${isEditInplace})];
	
	if (isEditInplace) {
		if (typeof(canEditInplace)=="function") {
			if (canEditInplace()) {
				initEditInPlace();
			}
		}
		else {
			initEditInPlace();
		}
	}

	[# th:if="${'search' eq op}"]
	// 必须得用setTimeout，否则因为jquery的document.ready赋值顺序问题，表单serial后所取得的参数为空
	setTimeout(function() {
		doQuery();
	}, 0)
	[/]
});

function del(ids) {
	layer.confirm('您确定要删除么？', {icon: 3, title: '提示'}, function (index) {
		try {
			onBeforeModuleDel(ids);
		} catch (e) {
		}

		$.ajax({
			type: "post",
			url: "moduleDelRelate.do",
			data: {
				code: "[(${moduleCodeRelated})]",
				mode: "[(${mode})]",
				parentId: "[(${parentId})]",
				parentModuleCode: "[(${moduleCode})]",
				ids: ids
			},
			dataType: "html",
			beforeSend: function(XMLHttpRequest){
				$("body").showLoading();
			},
			success: function(data, status){
				data = $.parseJSON(data);
				jAlert(data.msg, "提示");
				if (data.ret=="1") {
					doQuery();
					try {
						onModuleDel[(${moduleCodeRelated})](ids);
					}
					catch (e) {}
				}
			},
			complete: function(XMLHttpRequest, status){
				$("body").hideLoading();
			},
			error: function(XMLHttpRequest, textStatus){
				// 请求出错处理
				alert(XMLHttpRequest.responseText);
			}
		});
		layer.close(index);
	});
}

function edit(id) {
	var tabId = getActiveTabId();
	addTab("[(${moduleName})]", "visual/moduleEditRelatePage.do?mode=[(${mode})]&code=[(${moduleCode})]&parentId=[(${parentId})]&id=" + id + "&menuItem=[(${menuItem})]&moduleCodeRelated=[(${moduleCodeRelated})]&formCode=[(${formCode})]&tabIdOpener=" + tabId);
}
</script>
</html>
